const glob = require("glob");
const path = require("path");
const { sep } = path;
const _ = require("lodash");

// 项目配置继承模型配置
const projectExtendModel = (model, project) => {
  return _.mergeWith({}, model, project, (modelValue, projValue) => {
    if (Array.isArray(modelValue) && Array.isArray(projValue)) {
      // 创建结果数组，初始化为模型数组的副本
      const result = [...modelValue];
      
      // 处理项目数组中的每一项
      projValue.forEach((projItem) => {
        // 检查项目项是否已存在于模型数组中
        const existingIndex = modelValue.findIndex((modelItem) => 
          modelItem.key === projItem.key
        );
        
        if (existingIndex >= 0) {
          // 如果存在，用项目项覆盖模型项（递归合并）
          result[existingIndex] = projectExtendModel(modelValue[existingIndex], projItem);
        } else {
          // 如果不存在，添加项目项到结果数组
          result.push(projItem);
        }
      });
      
      return result;
    }
  });
};

module.exports = (app) => {
  const modelList = [];

  const modelPath = path.resolve(app.baseDir, `.${sep}model`);
  const fileList = glob.sync(path.resolve(modelPath, `.${sep}**${sep}**.js`));
  fileList.forEach((file) => {
    if (file.indexOf(`${sep}index.js`) > -1) {
      return;
    }
    const type = file.indexOf(`${sep}project${sep}`) > -1 ? "project" : "model";

    if (type === "model") {
      const modelKey = file.match(/\/model\/(.*?)\/model\.js/)?.[1];
      let modelItem = modelList.find((item) => {
        return item.model?.key === modelKey;
      });
      if (!modelItem) {
        modelItem = {};
        modelList.push(modelItem);
      }
      modelItem.model = require(path.resolve(file));
      modelItem.model.key = modelKey;
    }
    if (type === "project") {
      const modelKey = file.match(/\/model\/(.*?)\/project/)?.[1];
      const projKey = file.match(/\/project\/(.*?).js/)?.[1];

      let modelItem = modelList.find((item) => {
        return item.model?.key == modelKey;
      });
      if (!modelItem) {
        modelItem = {};
        modelList.push(modelItem);
      }
      if (!modelItem.project) {
        modelItem.project = {};
      }
      modelItem.project[projKey] = require(path.resolve(file));
      modelItem.project[projKey].key = projKey;
      modelItem.project[projKey].modelKey = modelKey;
    }
  });

  // project 继承 model
  modelList.forEach((item) => {
    const { model, project } = item;
    for (const key in project) {
      project[key] = projectExtendModel(model, project[key]);
    }
  });
  return modelList;
};
